/**
 * 存放位置 列表页 JS 脚本
 * @author 金杰 , maillank@qq.com
 * @since 2021-10-12 12:47:14
 */


function ListPage() {

    var settings,admin,form,table,layer,util,fox,upload,xmSelect;
    //模块基础路径
    const moduleURL="/service-ops/ops-statistics";
    var dataTable=null;
    var sort=null;

    var nodeId=NODE_ID;

    var formatDateTime = function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h=h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second=date.getSeconds();
        second=second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d+' '+h+':'+minute;
    };
    var lineOption= {
        legend: {
            orient: 'horizontal',
            show:true,
            type:'plain',
            bottom:0,
            data:[],
        },
        grid: {
            x:80,
            backgroundColor: 'rgba(0,0,0,0)',
            borderWidth: 1,
            borderColor: '#ccc'
        },
        title:{
            x: 'center',
            show:true,
            text:"",
            textStyle:{
                fontSize: 15,
            }
        },
        tooltip: {
            trigger: 'axis',
            position:pt=>{
                return [pt[0],'10%']
            }
        },
        xAxis: {
            type: 'time',
            // splitNumber: 13,
            axisLabel: {
                formatter: function(value, index) {
                    return formatDateTime(new Date(value));
                }
            },
            boundaryGap: false
        },
        yAxis: {
            type: 'value',
            splitLine:{ show:true}
        },
        series: []
    };
    /**
     * 入口函数，初始化
     */
    this.init=function(layui) {
        admin = layui.admin,settings = layui.settings,form = layui.form,upload = layui.upload,laydate= layui.laydate;
        table = layui.table,layer = layui.layer,util = layui.util,fox = layui.foxnic,xmSelect = layui.xmSelect,dropdown=layui.dropdown;;
        echarts=layui.echarts;

        if(window.pageExt.list.beforeInit) {
            window.pageExt.list.beforeInit();
        }
        //渲染表格
        renderTable();
        //初始化搜索输入框组件
        initSearchFields();
        //绑定搜索框事件
        bindSearchEvent();
        //绑定按钮事件
        bindButtonEvent();
        //绑定行操作按钮事件
        bindRowOperationEvent();
        searchData();
    }



    function searchData(){
        var ps={};
        // var tpl=xmSelect.get("#nodeTpl",true).getValue("value");
        // console.log("tpl",tpl);
        // if(tpl&&tpl.length>0){
        //     ps.tplCode=tpl[0];
        // }else{
        //    // alert("请选择模版")
        //     return 1;
        // }
        ps.tplCode="";
        ps.nodeId=nodeId;
        ps.sdate="";
        ps.edate="";
        ps.day=5;
        var stime=$("#sTime-begin").val();
        var etime=$("#sTime-end").val();

        if(stime!=""){
            ps.sdate=stime;
        }
        if(etime!=""){
            ps.edate=etime;
        }

        var task=setTimeout(function(){layer.load(2);},1000);
        admin.post("/service-ops/ops-statistics/query-node-collect-data-graph", ps, function (data) {
           clearTimeout(task);
           layer.closeAll('loading');
            if (data.success) {
                var tplData=data.data.tplData;
                var nodata=true;
                var html="";
                $("#chartList").html(html);
                if(tplData.length>0){
                    for(var i=0;i<tplData.length;i++){
                        var graphData=tplData[i];
                        for(var j=0;j<graphData.length;j++){
                            if(j==0){
                            }
                            nodata=false;
                            // var gap="<div class=\"gap\"></div>";
                            var gap=" "
                            $("#chartList").append(gap);
                            var gData=graphData[j];
                            var graphType=gData.graphInfo.graphType;
                            if(graphType=="line" || graphType=="line_calculation"){
                                var gid="graph"+gData.graphInfo.id;
                                var html="<div class=\"card\" id=\""+gid+"\" style=\"width:50%;height:300px;margin-top:20px;padding-top:20px\"></div>";
                                $("#chartList").append(html);
                                lineOption.legend.data=gData.legendData;
                                lineOption.title.text=gData.graphInfo.name;
                                lineOption.series=gData.seriesData;
                                var gChart = echarts.init(document.getElementById(gid));
                                gChart.setOption(lineOption, true);
                            }else if(graphType=="table"){
                                // if(!(gData.tableData.header&&gData.tableData.route&&gData.tableData.data&&gData.tableData.name)){
                                //     continue;
                                // }
                                // var header=gData.tableData.header;
                                // var route=gData.tableData.route;
                                // var tableData=gData.tableData.data;
                                // var title=gData.graphInfo.name;
                                // var html="<div class=\"card_table\" style='width:50%;'> " +
                                //     "<div class=\"card_table_title\"> "+title+"</div>" +
                                //     "<table class=\"pure-table pure-table-bordered\" id=\"dataCpu\" style=\"width:50%;text-align:left;\">"
                                // html=html+"<tr>";
                                // for(var i=0;i<header.length;i++){
                                //     html=html+"<th>"+header[i]+"</th>";
                                // }
                                // html=html+"</tr>";
                                // for(var i=0;i<tableData.length;i++){
                                //     var obj=tableData[i];
                                //     html=html+"<tr>";
                                //     for(var k=0;k<route.length;k++){
                                //          html=html+"<td>"+obj[route[k]]+"</td>";
                                //     }
                                //     html=html+"</tr>";
                                // }
                                // html=html+"</table></div>";
                                // $("#chartList").append(html);
                            }

                        }
                    }
                }else{
                }
            } else {
            }
            if(nodata){
                $("#chartList").append("<span style='margin-top:50px;margin-left:50px;margin-bottom: 50px'>当前无数据</span>");
            }
        });

    }
    /**
     * 渲染表格
     */
    function renderTable() {
        $(window).resize(function() {
            fox.adjustSearchElement();
        });
        fox.adjustSearchElement();

        // setTimeout(renderTableInternal,1);
    };

    /**
     * 刷新表格数据
     */
    function refreshTableData(sortField,sortType,reset) {
        searchData();
    }


    /**
     * 获得已经选中行的数据,不传入 field 时，返回所有选中的记录，指定 field 时 返回指定的字段集合
     */
    function getCheckedList(field) {
        var checkStatus = table.checkStatus('data-table');
        var data = checkStatus.data;
        if(!field) return data;
        for(var i=0;i<data.length;i++) data[i]=data[i][field];
        return data;
    }

    function getRecentDay(day){
        var today = new Date();
        var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
        today.setTime(targetday_milliseconds);
        var tYear = today.getFullYear();
        var tMonth = today.getMonth();
        var tDate = today.getDate();
        tMonth = doHandleMonth(tMonth + 1);
        tDate = doHandleMonth(tDate);
        return tYear+"-"+tMonth+"-"+tDate+" 00:00:00";
    }
    function doHandleMonth(month){
        var m = month;
        if(month.toString().length == 1){
            m = "0" + month;
        }
        return m;
    }

    function initSearchFields() {
        fox.switchSearchRow(1);

        //渲染 systemId 下拉字段
        // fox.renderSelectBox({
        //     el: "nodeTpl",
        //     radio: true,
        //     size: "small",
        //     filterable: true,
        //     //转换数据
        //     searchField: "name", //请自行调整用于搜索的字段名称
        //     extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
        //     transform: function(data) {
        //         //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
        //         var opts=[];
        //         if(!data) return opts;
        //         for (var i = 0; i < data.length; i++) {
        //             if(!data[i]) continue;
        //             if(i==0){
        //                 opts.push({name:data[i].name,value:data[i].code,selected:true});
        //             }else{
        //                 opts.push({name:data[i].name,value:data[i].code});
        //             }
        //
        //         }
        //         return opts;
        //     }
        // });


        var start=laydate.render({
            elem: '#sTime-begin',
           // max:0,
            type:'datetime',
            value:getRecentDay(0),
            trigger:"click",
            done:function(value,date) {
                if (value && (value > $("#sTime-end").val())) {
                     $("#end_date").val("");
                }
                end.config.min = {
                    year: date.year,
                    month: date.month - 1,
                    date: date.date,
                };
            }

        });

        var end=laydate.render({
            elem: '#sTime-end',
            // max:1,
            type:'datetime',
            value: getRecentDay(1),
            trigger:"click",
            done:function(value,date) {
                start.config.max = {
                    year: date.year,
                    month: date.month - 1,
                    date: date.date,
                }
            }
        });
        fox.renderSearchInputs();
        window.pageExt.list.afterSearchInputReady && window.pageExt.list.afterSearchInputReady();
    }

    /**
     * 绑定搜索框事件
     */
    function bindSearchEvent() {
        //回车键查询
        $(".search-input").keydown(function(event) {
            if(event.keyCode !=13) return;
            refreshTableData(null,null,true);
        });


        // 搜索按钮点击事件
        $('#search-button').click(function () {
            refreshTableData(null,null,true);
        });

        // 搜索按钮点击事件
        $('#last_data').click(function () {
            var d={}
            d.nodeId=nodeId;
            if(!nodeId){
                return 1;
            }
            if(nodeId=="none"){
                return 1;
            }
            console.log("ddd",d);
            admin.putTempData('eam-report-form-data', d);
            var area=admin.getTempData('eam-report-form-area');
            var height= (area && area.height) ? area.height : ($(window).height()*0.6);
            var title = fox.translate('最新数据');
            top=8;
            var index=admin.popupCenter({
                title: title,
                resize: false,
                offset: [20,null],
                area: ["80%","95%"],
                type: 2,
                id:"eam-report-form-data-win",
                content: '/business/ops/monitor_node_resource/monitor_node_collect_data.html?nodeId=' + d.nodeId,
                finish: function () {
                }
            });
            admin.putTempData('eam-report-form-data-popup-index', index);

        });

        fox.renderSearchInputs();

        // 搜索按钮点击事件
        $('#search-button-advance').click(function () {
            fox.switchSearchRow(1,function (ex){
                if(ex=="1") {
                    $('#search-button-advance span').text("关闭");
                } else {
                    $('#search-button-advance span').text("更多");
                }
            });
        });

    }

    /**
     * 绑定按钮事件
     */
    function bindButtonEvent() {

        //头工具栏事件
        table.on('toolbar(data-table)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var selected=getCheckedList("id");
            if(window.pageExt.list.beforeToolBarButtonEvent) {
                var doNext=window.pageExt.list.beforeToolBarButtonEvent(selected,obj);
                if(!doNext) return;
            }
            switch(obj.event){
                case 'refresh-data':
                    refreshTableData();
                    break;
                case 'other':
                    break;
            };
        });


    }

    /**
     * 绑定行操作按钮事件
     */
    function bindRowOperationEvent() {
        // 工具条点击事件
        table.on('tool(data-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if(window.pageExt.list.beforeRowOperationEvent) {
                var doNext=window.pageExt.list.beforeRowOperationEvent(data,obj);
                if(!doNext) return;
            }

            admin.putTempData('eam-position-form-data-form-action', "",true);
            if (layEvent === 'view') { // 查看
                //延迟显示加载动画，避免界面闪动
                var task=setTimeout(function(){layer.load(2);},1000);
                admin.request(moduleURL+"/get-by-id", { id : data.id }, function (data) {
                    clearTimeout(task);
                    layer.closeAll('loading');
                    if(data.success) {
                        admin.putTempData('eam-report-form-data-form-action', "view",true);
                        showEditForm(data.data);
                    } else {
                        layer.msg(data.message, {icon: 1, time: 1500});
                    }
                });
            }


        });

    };

    /**
     * 打开编辑窗口
     */
    function showEditForm(data) {
        if(window.pageExt.list.beforeEdit) {
            var doNext=window.pageExt.list.beforeEdit(data);
            if(!doNext) return;
        }
        var action=admin.getTempData('eam-report-form-data-form-action');
        var queryString="";
        if(data && data.id) queryString="?" + 'id=' + data.id;
        admin.putTempData('eam-report-form-data', data);
        var area=admin.getTempData('eam-report-form-area');
        var height= (area && area.height) ? area.height : ($(window).height()*0.6);
        var top= (area && area.top) ? area.top : (($(window).height()-height)/2);
        var title = fox.translate('存放位置');
        if(action=="create") title=fox.translate('添加')+title;
        else if(action=="edit") title=fox.translate('修改')+title;
        else if(action=="view") title=fox.translate('查看')+title;

        var index=admin.popupCenter({
            title: title,
            resize: false,
            offset: [top,null],
            area: ["80%",height+"px"],
            type: 2,
            id:"eam-report-form-data-win",
            content: '/business/eam/position/position_form.html' + queryString,
            finish: function () {
                refreshTableData();
            }
        });
        admin.putTempData('eam-report-form-data-popup-index', index);
    };

    function showNodeData(node){
        nodeId=node;
        searchData();
        //设置刷新下拉框
        // admin.request("/service-ops/monitor-data-process-base/query-tpl-list-by-node-id", { nodeId : nodeId }, function (data) {
        //     if(data.success){
        //         var d=data.data;
        //         var dArr=[];
        //         for(var i=0;i<d.length;i++){
        //             var e={};
        //             if(i==0){
        //                 e.selected=true;
        //             }
        //             e.value=d[i].code;
        //             e.name=d[i].name;
        //             dArr.push(e);
        //         }
        //         var selectTpl = xmSelect.get('#nodeTpl', true);
        //         if (selectTpl) {
        //             selectTpl.update({data: dArr})
        //
        //         }
        //         searchData();
        //     }
        // });
    }
    window.showNodeData=showNodeData;
    window.module={
        showNodeData:showNodeData,
        refreshTableData: refreshTableData,
        getCheckedList: getCheckedList
    };

    window.pageExt.list.ending && window.pageExt.list.ending();

};


layui.use(['form', 'table', 'util', 'settings', 'admin', 'upload','foxnic','xmSelect','laydate','dropdown'],function() {
    var task=setInterval(function (){
        if(!window["pageExt"]) return;
        clearInterval(task);
        (new ListPage()).init(layui);
    },1);
});